//
//  MyOutpatientTableViewController.m
//  LPTClient
//
//  Created by apple on 2018/12/7.
//  Copyright © 2018 zhaodd. All rights reserved.
//

#import "MyOutpatientTableViewController.h"
#import "MMProgressHUD.h"

@interface MyOutpatientTableViewController ()

@property (nonatomic, strong) NSDictionary *m_dict;

@end

@implementation MyOutpatientTableViewController

+ (instancetype)instance
{
    UIStoryboard * storyBoard = [UIStoryboard storyboardWithName:@"Mine" bundle:nil];
    MyOutpatientTableViewController *vc = [storyBoard instantiateViewControllerWithIdentifier:@"MyOutpatientTableViewController"];
    return vc;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self requestList];
    [self addSubViewsHere];
}

- (void)originDict
{
    
    self.m_dict = @{
                    @"1" : @{ @"1":@(0), @"2":@(0) },
                    @"2" : @{@"1":@(0), @"2":@(0) } ,
                    @"3" : @{@"1":@(0), @"2":@(0) } ,
                    @"4" : @{@"1":@(0), @"2":@(0) } ,
                    @"5" : @{@"1":@(0), @"2":@(0) } ,
                    @"6" : @{@"1":@(0), @"2":@(0) } ,
                    @"7" : @{@"1":@(0), @"2":@(0) }
                    
                    };
    
}
- (void)requestList
{
    [MMProgressHUD showWithStatus:@"加载中"];
    
    NSString *apiName = @"/api/scheduling_detail";
    LPTBaseRequest  *requset = [[LPTBaseRequest alloc] initWithApi:apiName withBody:@{} withMethod:YTKRequestMethodGET];
    
    [requset startRequestCompleteSuccess:^(__kindof LPTBaseRequest * _Nullable request, id  _Nonnull data, NSInteger code) {
        
        [MMProgressHUD dismiss];
        self.m_dict = data[@"scheduling"];
        if (self.m_dict) {
            if (![self.m_dict isKindOfClass:[NSDictionary class]]) {
                [self originDict];
            }
            if ([self.m_dict isKindOfClass:[NSDictionary class]]) {
                if ([self.m_dict allKeys] == 0) {
                    [self originDict];
                }
            }

            [self setupButtons];
        }
        
    } completeFailed:^(__kindof LPTBaseRequest * _Nullable request, id  _Nonnull data, NSInteger code) {
        [MMProgressHUD dismissWithError:request.msg];
    }];
    
}


- (void)requestSave
{
    [MMProgressHUD showWithStatus:@"保存中"];
    
    NSString *apiName = @"/api/scheduling_save";
    NSDictionary *body = @{@"scheduling": self.m_dict };
    LPTBaseRequest  *requset = [[LPTBaseRequest alloc] initWithApi:apiName withBody:body withMethod:YTKRequestMethodPOST];
    
    [requset startRequestCompleteSuccess:^(__kindof LPTBaseRequest * _Nullable request, id  _Nonnull data, NSInteger code) {
        [MMProgressHUD dismissWithSuccess:@"保存成功"];
        [self requestList];
        
    } completeFailed:^(__kindof LPTBaseRequest * _Nullable request, id  _Nonnull data, NSInteger code) {
        [MMProgressHUD dismissWithError:request.msg];
    }];
    
}

- (void)addSubViewsHere
{
    float weakWidth = 100;
    float jianXi = 4;
    float contentWidth = (kScreenWidth - 4*jianXi - weakWidth )/2;
    float height = 40;
    
    NSArray *array1 = @[@"星期/时间", @"周一", @"周二", @"周三", @"周四", @"周五", @"周六", @"周日"];
    NSArray *array2 = @[@"上午", @"", @"", @"", @"", @"", @"", @""];
    NSArray *array3 = @[@"下午", @"", @"", @"", @"", @"", @"", @""];
    NSArray *array = @[array1, array2, array3];
    
    
    for (int i=0; i<3; i++) {
        float width = (i==0)?weakWidth:contentWidth;
        NSArray *ar = array[i];
        float x = jianXi;
        if (i==1) {
            x = jianXi + weakWidth + jianXi;
        }else if (i==2) {
            x = jianXi + weakWidth + jianXi + (jianXi + contentWidth);
        }
        for (int j=0; j<8; j++) {
            UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
            btn.frame = CGRectMake(x, jianXi + j * (height + jianXi), width, height);
            btn.tag = 10 * i + j;
            btn.backgroundColor = [UIColor whiteColor];
            if (i == 0 && j == 0) {
                btn.titleLabel.font = [UIFont systemFontOfSize:13];
            }else
            if (i > 0 && j == 0) {
                btn.titleLabel.font = [UIFont systemFontOfSize:15];
            } else
            if (j > 0 && i == 0) {
                btn.titleLabel.font = [UIFont systemFontOfSize:15];
            } else {
                btn.titleLabel.font = [UIFont systemFontOfSize:14];
                [btn addTarget:self action:@selector(selectedButton:) forControlEvents:UIControlEventTouchUpInside];
            }

            [btn setBackgroundImage:[UIImage imageWithColor:[UIColor whiteColor]] forState:UIControlStateNormal];
            [btn setBackgroundImage:[UIImage imageWithColor:[UIColor colorWithHexString:@"#F7941E"]] forState:UIControlStateSelected];
            [btn setTitle:ar[j] forState:UIControlStateNormal];
            [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
            [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
            [self.view addSubview:btn];
        }
        
    }
    
    UIButton *commitBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    commitBtn.frame = CGRectMake(15, 10 + jianXi + 8 * (height + jianXi), kScreenWidth - 30, 45);
    commitBtn.backgroundColor = [UIColor whiteColor];
    [commitBtn.layer setMasksToBounds:YES];
    [commitBtn.layer setCornerRadius:22.5];
//    [commitBtn setBackgroundImage:[UIImage imageWithColor:[UIColor whiteColor]] forState:UIControlStateNormal];
    [commitBtn setBackgroundImage:[UIImage imageWithColor:[UIColor colorWithHexString:@"#F7941E"]] forState:UIControlStateNormal];
    [commitBtn addTarget:self action:@selector(commitButton:) forControlEvents:UIControlEventTouchUpInside];
    [commitBtn setTitle:@"保存" forState:UIControlStateNormal];
    [self.view addSubview:commitBtn];
}

- (void)setupButtons
{
    for (int i=1; i<3; i++) {
        
        for (int j=1; j<8; j++) {
            
            NSString *key = [NSString stringWithFormat:@"%d", j];
            NSDictionary *day_m = [self.m_dict valueForKey:key];
            
            NSString *key_day = [NSString stringWithFormat:@"%d", i];
            NSInteger rs = [[day_m valueForKey:key_day] integerValue];
            
            NSInteger tag = 10 * i + j;
            UIButton *button = (UIButton*)[self.view viewWithTag:tag];
            [button setTitle:(rs==1)?@"坐诊":@"空闲" forState:UIControlStateNormal];
            [button setSelected:(rs==1)?YES:NO];
        }
    }

}

- (void)commitButton:(UIButton *)button
{
    // 保存
    [self requestSave];
}

- (void)selectedButton:(UIButton *)button
{
    [button setSelected:![button isSelected]];
    [button setTitle:([button isSelected])?@"坐诊":@"空闲" forState:UIControlStateNormal];

    NSInteger tag = button.tag;
    
    NSInteger day = tag/10;// 1上午、2下午
    NSInteger weak = tag%10;//
    
    NSString *weak_key = [NSString stringWithFormat:@"%ld", weak];
    NSString *day_key = [NSString stringWithFormat:@"%ld", day];

    NSMutableDictionary *mainDict = [NSMutableDictionary dictionaryWithDictionary:self.m_dict];
    
    NSMutableDictionary *mutableDict = [NSMutableDictionary dictionaryWithDictionary:self.m_dict[weak_key]];
    [mutableDict setValue:[button isSelected]?@"1":@"0" forKey:day_key];
    
    [mainDict setValue:[mutableDict copy] forKey:weak_key];
    
    self.m_dict = [mainDict copy];
    
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 0;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 0;
}

/*
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:<#@"reuseIdentifier"#> forIndexPath:indexPath];
    
    // Configure the cell...
    
    return cell;
}
*/

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
